package com.example.demo.threadpool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPool {


    /**
     * 线程池的execute方法和submit方法比较
     * <T> Future<T> submit(Callable<T> task);            返回Future对象，通过get获取
     * <T> Future<T> submit(Runnable task, T result);     返回Future对象,传入什么返回什么
     * Future<?> submit(Runnable task);
     * void execute(Runnable command);
     * <p>
     * 1.execute 只能实现Runable，无返回值
     * 2.submit 可以实现Runable和Callable ,实现无返回值和有返回值
     * 2.execute 无返回值，submit 返回future对象
     */


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //execute方法
        for (int i = 0; i < 7; i++) {
            final int index = i;
            pool.execute(new Runnable() {

                @Override
                public void run() {
                    System.out.println("时间是:" + System.currentTimeMillis() + "第" + index + "个线程" + Thread.currentThread().getName());

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }


                }
            });

        }
        //submit方法 submit(Runnable task, T result);     返回Future对象,传入什么返回什么
        Future<String> gg = pool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "gg");

        System.out.println(gg.get());

    }


}
